<template>
  <div class="fill-container">
    <div v-if="questionnaire.state !== 1" class="not-available">
      <h2>{{ questionnaire.state === 0 ? '问卷尚未发布' : '问卷已结束' }}</h2>
      <button @click="$router.push('/')">返回首页</button>
    </div>
    
    <div v-else class="questionnaire-content">
      <h2>{{ questionnaire.title }}</h2>
      
      <div class="questions">
        <div v-for="(question, index) in questionnaire.questions" :key="index" class="question">
          <h3>
            {{ index + 1 }}. {{ question.topic }}
            <span v-if="question.isMandatory" class="mandatory">*</span>
          </h3>
          
          <!-- 单选题 -->
          <div v-if="question.type === 'radio'" class="options">
            <div v-for="(option, optIndex) in question.options" :key="optIndex" class="option">
              <input 
                type="radio" 
                :name="'question' + index"
                :id="'q' + index + 'opt' + optIndex"
                :value="optIndex"
                v-model="answers[`Q${index + 1}answer`]"
                :required="question.isMandatory"
              >
              <label :for="'q' + index + 'opt' + optIndex">{{ option }}</label>
            </div>
          </div>
          
          <!-- 多选题 -->
          <div v-else-if="question.type === 'checkbox'" class="options">
            <div v-for="(option, optIndex) in question.options" :key="optIndex" class="option">
              <input 
                type="checkbox"
                :id="'q' + index + 'opt' + optIndex"
                :value="optIndex"
                v-model="answers[`Q${index + 1}answer`]"
              >
              <label :for="'q' + index + 'opt' + optIndex">{{ option }}</label>
            </div>
          </div>
          
          <!-- 文本题 -->
          <div v-else-if="question.type === 'textarea'" class="text-answer">
            <textarea 
              v-model="answers[`Q${index + 1}answer`]"
              :required="question.isMandatory"
              rows="4"
              placeholder="请输入您的答案"
            ></textarea>
          </div>
        </div>
      </div>
      
      <div class="submit-section">
        <button @click="submitQuestionnaire" :disabled="submitting">
          {{ submitting ? '提交中...' : '提交问卷' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'FillComponent',
  data() {
    return {
      questionnaire: {},
      answers: {},
      submitting: false
    }
  },
  created() {
    this.loadQuestionnaire()
    this.initializeAnswers()
  },
  methods: {
    loadQuestionnaire() {
      const questionnaireId = this.$route.params.id
      const questionnaires = JSON.parse(localStorage.getItem('questionnaire') || '[]')
      this.questionnaire = questionnaires.find(q => q.id === parseInt(questionnaireId)) || {}
    },
    initializeAnswers() {
      this.questionnaire.questions?.forEach((question, index) => {
        if (question.type === 'checkbox') {
          this.answers[`Q${index + 1}answer`] = []
        } else {
          this.answers[`Q${index + 1}answer`] = ''
        }
      })
    },
    validateAnswers() {
      for (let i = 0; i < this.questionnaire.questions.length; i++) {
        const question = this.questionnaire.questions[i]
        const answer = this.answers[`Q${i + 1}answer`]
        
        if (question.isMandatory) {
          if (Array.isArray(answer) && answer.length === 0) {
            return false
          }
          if (!Array.isArray(answer) && (!answer || answer.trim() === '')) {
            return false
          }
        }
      }
      return true
    },
    async submitQuestionnaire() {
      if (!this.validateAnswers()) {
        alert('请填写所有必填项')
        return
      }

      this.submitting = true
      
      try {
        // 获取现有答案
        const allAnswers = JSON.parse(localStorage.getItem('questionnaire_answers') || '{}')
        if (!allAnswers[this.questionnaire.id]) {
          allAnswers[this.questionnaire.id] = []
        }
        
        // 添加新答案
        allAnswers[this.questionnaire.id].push({
          ...this.answers,
          submitTime: new Date().toISOString()
        })
        
        // 保存答案
        localStorage.setItem('questionnaire_answers', JSON.stringify(allAnswers))
        
        alert('提交成功！')
        this.$router.push('/')
      } catch (error) {
        alert('提交失败，请重试')
        console.error(error)
      } finally {
        this.submitting = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.fill-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;

  .not-available {
    text-align: center;
    padding: 50px;
    
    h2 {
      color: #ee7419;
      margin-bottom: 20px;
    }
    
    button {
      padding: 10px 20px;
      background: #ee7419;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      
      &:hover {
        background: #d65f0a;
      }
    }
  }

  .questionnaire-content {
    background: white;
    padding: 30px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.1);

    h2 {
      text-align: center;
      margin-bottom: 30px;
      color: #333;
      font-size: 24px;
    }

    .question {
      margin-bottom: 30px;

      h3 {
        margin-bottom: 15px;
        color: #333;
        
        .mandatory {
          color: #ff4d4f;
          margin-left: 5px;
        }
      }

      .options {
        .option {
          margin-bottom: 10px;
          
          input {
            margin-right: 10px;
          }
          
          label {
            color: #666;
          }
        }
      }

      .text-answer {
        textarea {
          width: 100%;
          padding: 10px;
          border: 1px solid #ddd;
          border-radius: 4px;
          resize: vertical;
          
          &:focus {
            outline: none;
            border-color: #ee7419;
          }
        }
      }
    }

    .submit-section {
      text-align: center;
      margin-top: 30px;
      
      button {
        padding: 12px 30px;
        background: #ee7419;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 16px;
        
        &:hover:not(:disabled) {
          background: #d65f0a;
        }
        
        &:disabled {
          background: #ccc;
          cursor: not-allowed;
        }
      }
    }
  }
}
</style>
